from django.db.models import Q

from content_center.models import Content


class ContentRepository:
    def get_contents(self, **kwargs) -> (int, list[Content]):
        q = Q()
        if content_id := kwargs.get("content_id"):
            q &= Q(id=content_id)
        if university_label_ids := kwargs.get("university_label_ids"):
            q &= Q(university_labels__in=university_label_ids)
        if sport_label_ids := kwargs.get("sport_label_ids"):
            q &= Q(sport_labels__in=sport_label_ids)
        if content_type := kwargs.get("content_type"):
            q &= Q(content_type=content_type)
        if author_name_contains := kwargs.get("author_name_contains"):
            q &= Q(author_name__contains=author_name_contains)
        if author_id := kwargs.get("author_id"):
            q &= Q(author_id=author_id)
        if title_contains := kwargs.get("title_contains"):
            q &= Q(title__contains=title_contains)
        if text_contains := kwargs.get("text_contains"):
            q &= Q(content_text__contains=text_contains)
        if brief_introduction_contains := kwargs.get("brief_introduction_contains"):
            q &= Q(brief_introduction__contains=brief_introduction_contains)
        if content_contains := kwargs.get("content_contains"):
            q &= Q(content__contains=content_contains)
        q &= Q(is_deleted=False)
        objs = Content.objects.filter(q).order_by("-update_time")
        total = objs.count()
        if (page_no := kwargs.get("page_no")) and (
                page_size := kwargs.get("page_size")
        ):
            offset = (page_no - 1) * page_size
            objs = objs[offset: offset + page_size]
        objs = objs.select_related("author").prefetch_related(
            "university_labels", "sport_labels"
        )
        return total, list(objs)
